package com.denlaku.longan.aspect;

import java.util.Collection;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import com.denlaku.longan.core.Current;
import com.denlaku.longan.vo.Base;
import com.denlaku.longan.vo.TenantBase;

/**
 * 操作信息赋值切面
 *
 * @author tianx
 */
@Component
@Aspect
public class VarOpAspect {
	@Before("@annotation(com.denlaku.longan.anno.VarOp)")
	public void before(JoinPoint jp) {
		Object[] args = jp.getArgs();
		if (args == null || args.length == 0) {
			return;
		}
		Long userId = Current.getUserId();
		Long tenantId = Current.getTenantId();
        for (Object arg : args) {
            setDefault(arg, userId, tenantId);
        }
	}
	
	private void setDefault(Object data, Long userId, Long tenantId) {
		if (data instanceof TenantBase base) {
            base.setCreatedBy(userId);
            base.setUpdatedBy(userId);
            base.setTenantId(tenantId);
		} else if (data instanceof Base base) {
            base.setCreatedBy(userId);
			base.setUpdatedBy(userId);
		} else if (data instanceof Collection<?>) {
			((Collection<?>) data).forEach(item -> setDefault(item, userId, tenantId));
		}
	}
}
